import WindowEventPublisher from '../../utils/window-event/addEvent';

// 微信支付文档：https://pay.weixin.qq.com/wiki/doc/apiv3/index.shtml
// 微信JSAPI支付，微信内H5调起支付(JSAPI调起支付API)
export class WxJSAPIPayment {
  pay(payInfoObj) {
    return new Promise((resolve, reject) => {
      try {
        function wxJSAPIPayCallBack(event) {
          if (event.data.name == "event" && event.data.value == "WxJSAPIPayBack") {
            // 移除监听
            WindowEventPublisher.removeListener("message", wxJSAPIPayCallBack);
            event.data.msg ? reject(event.data.msg) : resolve();
          }
        }

        WindowEventPublisher.addListener("message", wxJSAPIPayCallBack);

        // iframe外侧唤起微信支付
        parent.postMessage(
          {
            name: "WxJSAPIPay",
            value: payInfoObj,
          },
          window.location.origin
        );
      } catch (error) {
        reject(error);
      }
    });
  }
}

